import _ from 'lodash'
import React, { ReactNode } from 'react'
import { UdPage, BasePage, UdPageHeader, IBaseDetailPageProps, IBaseDetailPageState, UdDetail, udConfigProvider } from '../..'
import { Spin, Affix, BackTop } from 'antd'
import classNames from 'classnames'

/** 基本详情页 */
class BaseDetailPage<
  P extends IBaseDetailPageProps = IBaseDetailPageProps,
  S extends IBaseDetailPageState = IBaseDetailPageState>
  extends BasePage<P, S> {

  protected pageContainer = udConfigProvider.ui.getPageContainer()

  componentWillMount(otherState?: Partial<S>) {
    super.componentWillMount()
    let state: IBaseDetailPageState = {
      title: '',
      queryAction: (() => {
        if (process.env.NODE_ENV == 'development') {
          throw new Error('必须在子类中重写此状态，发起数据请求并且返回Promise。')
        }
      }) as any,
      querying: false,
      dataSource: {}
    }
    state = _.extend({}, state, otherState, this.state)
    this.setState(state)
  }

  componentDidMount() {
    this.query()
  }

  render(slot?: {
    body?: ReactNode
    footer?: ReactNode
  }) {
    let { title, querying } = this.state
    if (_.isFunction(title)) {
      title = title()
    }
    let footer: JSX.Element = null
    if (slot && slot.footer) {
      footer = <div className="detail-footer">{slot.footer}</div>
      if (this.pageContainer) {
        footer = <Affix offsetBottom={0} target={() => this.pageContainer}>{footer}</Affix>
      }
    }

    return (
      <UdPage className={classNames('detail-page', this.state.className)}>
        {
          title && <UdPageHeader title={this.state.title} subTitle={this.state.subTitle}
            onBack={this.onBack}
            affixProps={{ target: () => this.pageContainer }} />
        }
        <Spin spinning={querying}>
          <div className="detail-body">
            {slot && slot.body}
          </div>
          {footer}
        </Spin>
        {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}

      </UdPage>
    )
  }

  /** 发起查询 */
  query = () => {
    this.setState({ querying: true });
    this.state.queryAction().then(res => {
      let data = this.handleDataSource(res)
      this.setState({ dataSource: data })
    }).finally(() => {
      this.setState({ querying: false })
    })
  }

  /** query成功后处理数据 */
  handleDataSource = (res: any) => {
    return res.data
  }

  /** 返回 */
  onBack = () => {
    window.history.back()
  }

}

export default BaseDetailPage
